/**
 * 仓库管理操作记录
 */
import { Application } from "egg";
import { ObjectId } from "mongoose";
import * as AutoIncrementFactory from "mongoose-sequence";
import { WarehouseDrugProps } from "./Warehouse";
// import { FieldProps } from "./BasicField";
export interface OperateProps {
  name: string; // 操作人
  message: string; // 操作内容
  level: number; // 操作级别 2
}
interface WarehouseDataProps {
  _id: ObjectId; // 库存id
  drug: WarehouseDrugProps; // 药品信息
  productionDate: Date; // 生产日期【入库】
  expirationDate: Date; // 过期日期【入库】
  business: string; // 所属商业公司名称【各个分仓库】【入库】
  amount: number; // 当前库存【入库】
  batches: string; // 入库批号【入库】
  flow: []; // 药品流向【入库】
}
// TODO 为了后续方便统计，需增加如下字段
// 【1】把药品信息直接展示，而不是关联表
// 【2】商业级别需要好好计算，方便后续查询
// 【3】新增调拨的特殊记录，你减少，我就增多
// 【4】新增当前库存信息
export interface WarehouseRecordProps {
  _id: ObjectId;
  company_id: ObjectId; // 所属公司
  warehouse: WarehouseDataProps; // 库存ID
  output_name: string; // 输出方(药品调出方)
  receive_name: string; // 接收方ID【商业公司/医院】
  amount: number; // 数量【出库数量/入库数量/调拨数量/退货数量】
  level: number; // 商业级别
  type: string; // 操作类型【入库/出库/调拨/退货】
  operate_msg: OperateProps; // 操作信息
  is_delete: boolean; // 是否删除
  createdAt: number;
  updatedAt: number;
}
function initWarehouseRecordModel(app: Application) {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;
  const AutoIncrement = AutoIncrementFactory(mongoose);
  const WarehouseRecordScheme = new Schema<WarehouseRecordProps>(
    {
      company_id: {
        type: Schema.Types.ObjectId,
        ref: "Company",
        required: true,
      },
      warehouse: { type: Object, required: true },
      output_name: { type: String, required: true },
      receive_name: { type: String, required: true },
      amount: { type: Number },
      level: { type: Number, required: true },
      type: { type: String, required: true },
      operate_msg: { type: Object },
      is_delete: { type: Boolean, default: false },
      createdAt: { type: Number },
      updatedAt: { type: Number },
    },
    {
      timestamps: true,
      toJSON: {
        transform(_doc, ret) {
          delete ret.__v;
        },
      },
    }
  );
  WarehouseRecordScheme.plugin(AutoIncrement, {
    inc_field: "id",
    id: "WarehouseRecord_counter",
  });
  return mongoose.model<WarehouseRecordProps>(
    "WarehouseRecord",
    WarehouseRecordScheme
  );
}

export default initWarehouseRecordModel;
